package cn.edu.zjicm.wordsnet_d.synchronize;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.mime.HttpMultipartMode;
import org.apache.http.entity.mime.MultipartEntity;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.json.JSONObject;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Bitmap.CompressFormat;
import android.os.Handler;
import android.util.Log;
import cn.edu.zjicm.wordsnet_d.datapersistent.AppPreference;
import cn.edu.zjicm.wordsnet_d.download.JudgeNetwork;
import cn.edu.zjicm.wordsnet_d.util.BitmapUtil;

public class HeadImageInterface extends ServerInterface{

	private static HeadImageInterface mInstance;

	public static HeadImageInterface getInstance(Context context) {
		if (mInstance == null) {
			mInstance = new HeadImageInterface(context);
		}
		return mInstance;
	}

	private HeadImageInterface(Context context) {
		super(context);
	}
	
	public void upload(Bitmap photo, Handler handler) {
		if (JudgeNetwork.getInstance(context).isWifiConnected() || JudgeNetwork.getInstance(context).isMobileConnected()) {
			new UploadThread(photo, handler).start();
		} else {
			// Toast.makeText(context, "请确认网络是否连接", Toast.LENGTH_LONG).show();
			handler.sendMessage(handler.obtainMessage(UserInterface.MSG_BAD_NETWORK));
		}
	}
	
	public void downloadHeadImage() {
		if (JudgeNetwork.getInstance(context).isWifiConnected() || JudgeNetwork.getInstance(context).isMobileConnected()) {
			new DownloadHeadImageThread().start();
		} else {
			// Toast.makeText(context, "请确认网络是否连接", Toast.LENGTH_LONG).show();
//			handler.sendMessage(handler.obtainMessage(RegisterAndLogin.MSG_BAD_NETWORK));
		}
	}

	/*上传头像*/
	public class UploadThread extends Thread {
		Bitmap photo;
		String token;
		Handler handler;

		UploadThread(Bitmap photo, Handler handler) {
			this.token = AppPreference.getToken(context);
			this.photo = photo;
			this.handler = handler;
		}

		public void run() {
			String strHeadPortraitFilename = "temp_head_portrait.jpg";
			try {
				photo.compress(CompressFormat.JPEG, 100, context.openFileOutput(strHeadPortraitFilename, Context.MODE_PRIVATE));
			} catch (Exception e) {
				handler.sendMessage(handler.obtainMessage(UserInterface.MSG_WRONG_PHOTO));
				return;
			} catch (OutOfMemoryError e) {
				handler.sendMessage(handler.obtainMessage(UserInterface.MSG_WRONG_PHOTO));
				return;
			}
			
			File file = new File(context.getFilesDir(), strHeadPortraitFilename);
			
			DefaultHttpClient client = new DefaultHttpClient();
			setClientTimeout(client);
	
			MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
//			if (file.exists()) {				
				try {
					FileBody encFile = new FileBody(file);
					entity.addPart("Filedata", encFile);
					entity.addPart("key", new StringBody(AppPreference.getToken(context) + "_h"));
					
					HttpPost post = new HttpPost(UPLOAD);
					post.setEntity(entity);
					HttpResponse response = client.execute(post);

					if (response.getStatusLine().getStatusCode() == 200) {
						String str = EntityUtils.toString(response.getEntity(), "utf-8");
						JSONObject result = new JSONObject(str);
						String message = result.getString("message");
						boolean success = result.getBoolean("success");
						if (success) {
//							AppPreference.setDownloadPunchData(context, true);
							handler.sendMessage(handler.obtainMessage(UserInterface.MSG_SUCCESS));
						} else {
							handler.sendMessage(handler.obtainMessage(UserInterface.MSG_UNSUCCESS));
						}
					} else {
						handler.sendMessage(handler.obtainMessage(UserInterface.MSG_WEB_SITE_ACCESS_FAILURE));
					}
				} catch (UnsupportedEncodingException e) {
					Log.e("", "Failed to add form field.", e);
					handler.sendMessage(handler.obtainMessage(UserInterface.MSG_WEB_SITE_ACCESS_FAILURE));
				} catch (Exception e) {
					e.printStackTrace();
					handler.sendMessage(handler.obtainMessage(UserInterface.MSG_BAD_NETWORK));
				}
//			} else {
//				handler.sendMessage(handler.obtainMessage(RegisterAndLogin.MSG_WEB_SITE_ACCESS_FAILURE));
//			}

		}
	};	
	
	/* 下载用户头像线程 */
	public class DownloadHeadImageThread extends Thread {

//		private Handler handler;
//
//		public DownloadHeadImageThread(Handler handler) {
//			this.handler = handler;
//		}

		@Override
		public void run() {
			InputStream inputStream = null;
			Bitmap bitmap;
			int allSize;
			try {
				String path = HEAD_URL + AppPreference.getToken(context) + "_h";

				URL url = new URL(path);
				HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
				urlConnection.setConnectTimeout(30000);
				urlConnection.setReadTimeout(30000);
				urlConnection.connect();
				inputStream = urlConnection.getInputStream();

				allSize = urlConnection.getContentLength();// 根据响应获取文件大小
				if (allSize <= 0) { // 获取内容长度为0
					throw new NoContentException("无法获知文件大小 ");
				}
				if (inputStream == null || urlConnection.getURL() != url) { // 没有下载流
					throw new FileNotFoundException("没有下载流");
				}

				int responseCode = urlConnection.getResponseCode();
				if (responseCode == HttpURLConnection.HTTP_OK) {
					bitmap = BitmapFactory.decodeStream(inputStream);
					if (bitmap != null) {
						BitmapUtil.saveHeadPortrait(bitmap, context);
//						handler.sendMessage(handler.obtainMessage(MSG_SUCCESS));
//						LogUtil.e("下载文章预览图成功", "");
					} else {
//						handler.sendMessage(handler.obtainMessage(MSG_WEB_SITE_ACCESS_FAILURE));
					}
				} else {
//					handler.sendMessage(handler.obtainMessage(MSG_WEB_SITE_ACCESS_FAILURE));
				}
			} catch (NoContentException e) {
				e.printStackTrace();
//				LogUtil.e("Download error", "NoContentException");
//				handler.sendMessage(handler.obtainMessage(MSG_WEB_SITE_ACCESS_FAILURE));
			} catch (MalformedURLException e) { // 当组件的URL不存在或者不正确的时候会抛出以下异常(Malformed:扭曲地、丑陋地)
//				handler.sendMessage(handler.obtainMessage(MSG_WEB_SITE_ACCESS_FAILURE));
			} catch (IOException e) { // 在获取服务器文件时候传输出错或者链接被强行关闭将会抛出以下异常
//				handler.sendMessage(handler.obtainMessage(MSG_WEB_SITE_ACCESS_FAILURE));
				e.printStackTrace();
			} finally {
				try {
					if (inputStream != null) {
						inputStream.close();
						inputStream = null;
					}
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
	}

}
